<?php

class EHtmlHelper extends AppHelper
{
	var $helpers = Array("Html");
    static protected $sys_id = 0;
    static protected $sys_func = 0;
    const sys_prefix = '__sys__';
    protected $icons = array(
        "reports",
        "edit",
        "admining",
        "report_admining",
        "to_archive",
        "from_archive",
        "cancel",
        "calendar",
        "admins",
        "add",
        "download",
    );

    function js_replace_element($noscript, $script, $params = array())
    {
        static $num = 0;
        $var_name = null;
        if (isset($params['var_name'])) {
            $var_name =& $params['var_name'];
        }
        $result = '';
        $script_str = str_replace("'", "\\\'", $script);
        $result .= $noscript;
        $sys_id = $this->get_sys_id();
        $sys_ns = $this->get_sys_ns();
        $result .= '<script id="'.$sys_id.'" type="text/javascript">//<!--'."\n";
        $prefix_ns = self::sys_prefix . 'jre__';

        $var_name = empty($var_name) ? $prefix_ns.$num : $var_name;

        $assigned_add = is_null($var_name) ? '' : 'var '.$var_name.' = ';

        $script_node_var_name = $prefix_ns.'this_element';

        $js_code = <<<Heredoc
    var {$script_node_var_name} = document.getElementById('{$sys_id}');
    remove_node({$script_node_var_name}.previousSibling);
    doc_write('{$script_str}');
    {$assigned_add}{$script_node_var_name}.nextSibling;
    remove_node({$script_node_var_name});
Heredoc;
        $result .= $js_code;
        $result .= '//--></script>';

        return $result;
    }

    function get_sys_id()
    {
        return self::sys_prefix . self::$sys_id++;
    }

    function get_sys_ns()
    {
        return self::sys_prefix . self::$sys_func++;
    }

    function shadow_box($className, $content, $args = array())
    {

        $file_name['tl']    = $className.'-tl.png';
        $file_name['t']     = $className.'-t.png';
        $file_name['tr']    = $className.'-tr.png';
        $file_name['r']     = $className.'-r.png';
        $file_name['br']    = $className.'-br.png';
        $file_name['b']     = $className.'-b.png';
        $file_name['bl']    = $className.'-bl.png';
        $file_name['l']     = $className.'-l.png';

        $path = Application::rootUrlPath().'/img/';
        $out_before = "";

        $out_before .= '<div class="sys_box" style="'.$this->backgroundImageNotIE($path.$file_name['tl'], true).'">';
        $out_before .= '<div class="sys_ctr" style="'.$this->backgroundImageNotIE($path.$file_name['tr'], true).'">';
        $out_before .= '<div class="sys_cbl" style="'.$this->backgroundImageNotIE($path.$file_name['bl'], true).'">';
        $out_before .= '<div class="sys_cbr" style="'.$this->backgroundImageNotIE($path.$file_name['br'], true).'">';

        $out_before .= '<div class="sys_top" style="height: 8px; margin-left: 8px; margin-right: 8px; '.$this->backgroundImageNotIE($path.$file_name['t']).' //height: 0px; //margin-left: 0px; //margin-right: 0px;"></div>';

        $out_before .= '<div class="sys_left-container" style="'.$this->backgroundImageNotIE($path.$file_name['l']).'">';
        $out_before .= '<div class="sys_right-container" style="'.$this->backgroundImageNotIE($path.$file_name['r']).'">';
        $out_before .= '<div style="margin-left: 8px; margin-right: 8px; //margin-left: 0px; //margin-right: 0px;">';

        /*
        C O N T E N T
        */

        $out_after  = "";
        $out_after .= "</div>";
        $out_after .= "</div>";
        $out_after .= "</div>";

        $out_after .= '<div class="sys_bottom" style="height: 8px; margin-left: 8px; margin-right: 8px; '.$this->backgroundImageNotIE($path.$file_name['b']).' //height: 0px; //margin-left: 0px; //margin-right: 0px;"></div>';

        $out_after .= '</div>';
        $out_after .= '</div>';
        $out_after .= '</div>';
        $out_after .= '</div>';

        if (is_callable($content)) {
            echo $out_before;
            call_user_func_array($content, $args);
            echo $out_after;
        } else {
           return $out_before.$content.$out_after;
        }
    }

    function backgroundImage($url, $crop=false)
    {
        return "background-image:url({$url});";
    }

    function backgroundImageIE($url, $crop=false)
    {
        return "background-image:url({$url});filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='{$url}',sizingMethod='".($crop ? "crop" : "scale")."');//background-image: none;";
    }

    function backgroundImageNotIE($url, $crop=false)
    {
        return "background-image:url({$url});//background-image: none;";
    }

	function image($path, $htmlAttributes = array(), $return = false)
	{
		$result = '';

		$url = (strpos($path, '://') || ($path[0]=='/')) ? $path : Application::rootUrlPath().Application::imgUrlPath().'/'.$path;

		if (stripos($url, '.png')===strlen($url)-4) {
			$htmlAttributes = am($this->imageInfo($url), $htmlAttributes);
			if (empty($htmlAttributes["style"])) {
			    $htmlAttributes["style"] = '';
			} elseif ($htmlAttributes["style"][strlen($htmlAttributes["style"])-1]!==';') {
			    $htmlAttributes["style"] .= ';';
			}
			$htmlAttributes["style"] .= "background-image:url('{$url}');filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='{$url}',sizingMethod='scale');//background-image: none;";
			$result = $this->Html->image('pix.gif', $htmlAttributes, $return);
		} else {
			$result = $this->Html->image($path, $htmlAttributes, $return);
		}

		return $result;
	}

	function imageInfo($path)
	{
		$result = array();

		$url = '';
		if (strpos($path, '://')) {
		    $url = parse_url($path);
		    $url = (isset($url['path']) ? $url['path'] : "").(isset($url['query']) ? "?{$url['query']}" : "").(isset($url['fragment']) ? "#{$url['fragment']}" : "");
		} else {
            $url = $path;
		}
		$url = str_replace('/', Application::ds(), $url);
		$full_path = Application::docRootPath().$url;

		static $cash = array();

		if (!isset($cash[$full_path])) {
		    if (file_exists($full_path) && is_readable($full_path) && ((bool)($img_source = @imagecreatefrompng($full_path))) && is_resource($img_source)) {
    			$cash[$full_path]["width"]  = imagesx($img_source);
    			$cash[$full_path]["height"] = imagesy($img_source);
		    } else {
    			$cash[$full_path]["width"]  = 0;
    			$cash[$full_path]["height"] = 0;
		    }
		}
		$result["width"]  = $cash[$full_path]["width"];
		$result["height"] = $cash[$full_path]["height"];

		return $result;
	}

	function iconLink($type, $title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true)
	{
	    $args = func_get_args();
	    if (isset($args[3]["button"])) {
	        unset($args[3]["button"]);
	    }
	    return call_user_func_array(array($this, '_iconLink'), $args);
    }

	function iconButton($type, $htmlAttributes = array())
	{
	    $args = func_get_args();
	    $htmlAttributes = array();
	    if (isset($args[1])) {
            $htmlAttributes = $args[1];
	    }
	    $htmlAttributes["button"] = true;
	    if (!isset($args[0])) {
	        $args[0] = null;
	    }
	    $args[1] = null;
	    $args[2] = null;
	    $args[3] = $htmlAttributes;
	    return call_user_func_array(array($this, '_iconLink'), $args);
    }

	function _iconLink($type, $title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true)
	{
	    if (!in_array($type, $this->icons)) {
	        return "";
	    }
	    $index = array_keys($this->icons, $type, true);
	    if (!isset($index[0])) {
	        return "";
	    }
	    $index = $index[0];

	    $alert = null;
	    $inactive = !empty($htmlAttributes["inactive"]);
	    $alert = !empty($htmlAttributes["inactive"]) && is_string($htmlAttributes["inactive"]) ? str($htmlAttributes["inactive"])->addslashes("'\"")->value : "";
	    if (array_key_exists("inactive", $htmlAttributes)) {
	        unset($htmlAttributes["inactive"]);
	    }
	    if (is_string($confirmMessage)) {
            $__confirmMessage = str($confirmMessage)->addslashes("'\"")->value;
	    } else {
	        $__confirmMessage = false;
	    }
        $confirmMessage = false;
        if (empty($htmlAttributes["onclick"])) {
            $htmlAttributes["onclick"] = '';
        }
	    if ($inactive) {
	        $pre_action = $alert ? "alert('".$alert."');" : "";
            $action = $pre_action.'return false;';
	        $htmlAttributes["onclick"] = $action.$htmlAttributes["onclick"];
        } elseif (is_string($__confirmMessage)) {
            $action = "if (!confirm('".$__confirmMessage."')) return false;";
	        $htmlAttributes["onclick"] = $action.$htmlAttributes["onclick"];
        }
	    if (isset($htmlAttributes["class"])) {
	        $htmlAttributes["class"] .= " ";
	    } else {
	        $htmlAttributes["class"] = "";
	    }
	    $htmlAttributes["class"] .= "icon".$index.($inactive ? "i" : "");

	    $notable = !empty($htmlAttributes["notable"]);
	    if (array_key_exists("notable", $htmlAttributes)) {
	        unset($htmlAttributes["notable"]);
	    }
	    $button = !empty($htmlAttributes["button"]);
	    if (array_key_exists("button", $htmlAttributes)) {
	        unset($htmlAttributes["button"]);
	    }
	    if ($title) {
	       $htmlAttributes["title"] = $title;
	    }

	    $html = "";
	    if ($button) {
	        unset($htmlAttributes["button"]);
    	    $htmlAttributes["class"] .= " icon-button sys_clear";
    	    $button_content = '<img src="'.$this->url(Application::imgUrlPath().'/pix.gif').'" class="sys_clear filler" />';
    	    $html = '<button'.$this->_parseAttributes($htmlAttributes).'>'.$button_content.'</button>';
        } else {
    	    $htmlAttributes["class"] .= " icon-link";
    	    $title = "";

    	    $html = $this->Html->link($title, $url, $htmlAttributes, $confirmMessage, $escapeTitle);
    	    if (!$notable) {
        	    $html = '<td class="sys_clear">'.$html.'</td>';
    	    }
        }
	    return $html;
    }
}

?>
